<template>
  <div class="mg-top-16">
    <van-cell-group inset>
      <van-cell>
        <div class="my-flex-c" slot="title">
          <van-image round class="avatar-image" :src="state.userInfo?.avatar" />
          <div class="mg-left t-l" v-if="state.userInfo?.id">
            <div class="font-w">
              {{ state.userInfo?.nickname || "匿名用户" }}
            </div>
            <div>状态：{{ state.userInfo?.status_desc }}</div>
          </div>
          <div class="mg-left font-w" v-else>未登录</div>
        </div>
      </van-cell>
    </van-cell-group>
  </div>

  <div class="mg-top" v-if="state.userInfo?.status_desc">
    <van-cell-group inset>
      <van-cell title="用户状态" :value="state.userInfo?.status_desc" />
      <van-cell title="兑换积分" :value="state.userInfo?.salemanPoints" />
    </van-cell-group>
  </div>

  <div class="my-futter" v-if="state.token">
    <van-button size="large" round plain hairline @click="onLoginout">
      退出登录
    </van-button>
  </div>
  <LoginEvent v-else></LoginEvent>
</template>
<script setup>
import { reactive, onMounted } from "vue";
import api from "@/api/login.js";
import { removeLoginInfo } from "@/utils/loginInfo.js";
import { useRouter } from "vue-router";
import LoginEvent from "@/components/loginEvent.vue";

const router = useRouter();
const state = reactive({
  userInfo: localStorage.getItem("userInfo")
    ? JSON.parse(localStorage.getItem("userInfo"))
    : {
        avatar: "",
      },
  token: localStorage.getItem("accessToken") || "",
});

async function getUserInfo() {
  const res = await api.getUserInfo();
  console.log(1111111, res.data.user);
  if (res.code === 0) {
    state.userInfo = res.data.user;
  }
}

async function onLoginout() {
  const res = await api.logout();
  if (res.code === 0) {
    await removeLoginInfo();
    router.push({
      path: "/login",
    });
  }
}

onMounted(() => {
  if (localStorage.getItem("accessToken")) {
    getUserInfo();
  }
});
</script>

<style lang="less" scoped>
.avatar-wrapper {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 100px;
  margin-right: 20px !important;
}

.avatar-image {
  width: 100px;
  height: 100px;
}
</style>
